<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>chatroom</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/chatroomcss.css"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">

</head>
<body>

<div class="container">
    <aside>
        <div class="roomInfo">
            <p class="room">房间：xxxxx</p>
            <p class="user">昵称：zzzz</p>
            <br/>
            <span id="refreshOnlineUser">点击刷新房间内用户</span>
            <div class="online-user">
                <p>测试用户1</p>
            </div>
        </div>
    </aside>

    <div class="show-area" id="show-area">

    </div>

    <div class="input-area">
        <textarea id="myMsg"></textarea>
    </div>
</div>
</body>

<script>
    var socket;
    var userId = "test";
    var roomId = -1;
    openSocket();
    sendNick();

    function openSocket() {
        if(typeof (WebSocket)=="undefined"){
            console.log("浏览器不支持websocket！");
        }else {
            //获取房间id跟用户名id
            $.ajax({
                url:"/api/getId",
                async:false,    //若不设置，则无法再外部引用ajax里的数据。
                dataType:'json',
                success:function( mydata ){
                    console.log(mydata);
                    userId = mydata.userId;
                    roomId = mydata.roomId;
                    //在页面中设置房间名和登陆的用户名
                    setIdInnerHtml(userId,roomId);
                },
                fail:function () {
                    console.log("获取房间信息失败！");
                }
            });
            var socketUrl = "ws://localhost:8080/webSocket/"+userId;
            console.log("socketUrl: "+socketUrl);
            if (socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);

            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                var serverMsg =  msg.data;
                console.log("服务器发来的消息："+serverMsg);
                // 发现消息进入    开始处理前端触发逻辑
                // 处理数据，然后把消息显示到页面上的左边。
                var data = JSON.parse(msg.data);
                receiveMessageInnerHtml(data.userId, data.contentText);
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }

    //发送消息
    function sendMessage(){
        if ( typeof (WebSocket) == "undefined" ){
            console.log("你的浏览器不支持websocket！！")
        }else{
            // console.log("你的浏览器支持websocket.")
            var contentText = document.getElementById('myMsg').value;
            var msg = '{"contentText":"'+contentText+'","roomId":"'+roomId+'","userId":"'+userId+'"}';
            socket.send(msg);
        }
    }
    //发送房间号跟用户名
    function sendNick() {
        $.ajax({
            url:"/api/setId",
            data: {"roomId":roomId,"userId":userId},
            dataType:'json'
        })
    }

    $(function(){
        // 刷新房间内在线用户
        $("#refreshOnlineUser").click(function(){
            refreshOnlineUser();
        });

        //监听输入时发送的回车快捷键
        $(".input-area").keydown(function(e){
            if(e.keyCode == 13){
                //在页面显示，然后消除输入框内的内容
                var msg = document.getElementById('myMsg').value;
                showMessageInnerHtml(userId,msg);
                //发送出去--未实现
                sendMessage();
                //清空输入框
                document.getElementById('myMsg').value = "";
                event.preventDefault();
            }
        })
    })

    //显示自己发送的消息到页面上
    function showMessageInnerHtml(userId, msg){
        var contentDiv = '<div class="content-right"><div class="user-info"><p>'+userId+'</p></div><div class="msg"><p>'+msg+'</p></div></div>'
        $(".show-area").append(contentDiv);
        scrollBottom();
    }
    //显示收到的发送的消息到页面上
    function receiveMessageInnerHtml(userId, msg){
        var contentDiv = '<div class="content-left"><div class="user-info"><p>'+userId+'</p></div><div class="msg"><p>'+msg+'</p></div></div>'
        $(".show-area").append(contentDiv);
        scrollBottom();
    }
    //显示房间信息到页面上
    function setIdInnerHtml(userId, roomId){
        $(".room").text("房间Id："+roomId);
        $(".user").text("用户："+userId);
    }
    // 滚动条自动下移到最底部
    function scrollBottom(){
        var div = document.getElementById("show-area");
        div.scrollTop = div.scrollHeight;
    }
    // 刷新在线用户
    function refreshOnlineUser() {
        $.ajax({
            url:"/api/getOnlineUser",
            data: {"roomId":roomId},
            dataType:'json',
            success:function( callbackData ) {
                console.log(callbackData);
                var mydata =  callbackData.data;
                $(".online-user").text("");
                for ( var i=0; i<callbackData.length;i++ ){
                    var adiv = '<p>' + callbackData[i] + '</p>';
                    $(".online-user").append(adiv);
                }
            }
        })
    }
</script>
</html>
